package com.intretech.umsin.oss.util.huaweiobs.aspect;

/**
 * @version V1.0
 * @ClassName: ObsAspect
 * @Description: ObsAspect 服务实现
 * @author: 李启联
 * @date: 2021-06-05 16:56
 * @Copyright: Copyright (c) 2021
 */


import com.intretech.umsin.oss.util.huaweiobs.HuaweiOssProperties;
import com.intretech.umsin.oss.util.huaweiobs.ObsTemplate;
import com.obs.services.ObsClient;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;


/**
 * @version V1.0
 * @ClassName: ObsAspect
 * @Description: obs工具切面（为了创建和关闭obsClient）
 * @author: 李启联
 * @date: 2022-04-25 16:10
 * @Copyright: Copyright (c) 2022
 */
@Component
@Aspect
@Slf4j
public class ObsAspect {

    @Autowired
    private HuaweiOssProperties obsProperties;

    @Autowired(required = false)
    private ObsTemplate obsTemplate;

    /**
     * 定义切入点，前置和后置表达式都一样的所以定义在这里
     * 通过@Pointcut注解声明频繁使用的切点表达式
     */
    @Pointcut("@annotation(com.intretech.umsin.oss.util.huaweiobs.annotation.ObsClientAnnotation)")
    public void obsPointcut() {
    }

    @Before("obsPointcut()")
    public void init() {
        //创建客户端连接
        ObsClient obsClient = new ObsClient(obsProperties.getAk(), obsProperties.getSk(), obsTemplate.getConfig());
        obsTemplate.setObsClient(obsClient);
        log.info("======ObsTemplate init========");
    }

    @After("obsPointcut()")
    public void closeClient() {
        //关闭客户端连接
        if (obsTemplate.getObsClient() != null) {
            try {
                obsTemplate.getObsClient().close();
                obsTemplate.getTlObsClient().remove();
                log.info("======关闭obs客户端连接========");
            } catch (IOException e) {
                //e.printStackTrace();
                log.error("[ "+this.getClass()+" - 关闭obs客户端连接失败 ]",e);
            }
        }
    }

}
